package com.zbkj.service.settlement;

import cn.hutool.core.util.StrUtil;
import com.beust.jcommander.internal.Lists;
import com.zbkj.dal.base.constants.BrokerageRecordConstants;
import com.zbkj.dal.base.constants.GlobalConstants;
import com.zbkj.dal.base.constants.ProductConstants;
import com.zbkj.dal.entity.merchant.Merchant;
import com.zbkj.dal.entity.order.Order;
import com.zbkj.dal.entity.order.OrderDetail;
import com.zbkj.dal.entity.product.ProductAttrValue;
import com.zbkj.dal.entity.user.User;
import com.zbkj.dal.entity.user.UserBrokerageRecord;
import com.zbkj.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单分佣结算
 * @author tianzhonghai
 * 2023/10/6 12:26
 */
@SettleTypeAnno(value = SettlementConstants.ORDER)
@Component
@Slf4j
public class OrderSettleStrategy extends AbstractSettleStrategy {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UserService userService;

    @Override
    public List<UserBrokerageRecord> settle(String orderNo) {
        log.info("开始订单分佣结算，orderNo=" + orderNo);
        List<UserBrokerageRecord> records = Lists.newArrayList();
        Order order = orderService.getByOrderNo(orderNo);
        if (order.getIsDel()) {
            return records;
        }
//        if (!ObjectUtils.nullSafeEquals(OrderConstants.ORDER_STATUS_TAKE_DELIVERY, order.getStatus())) {
//            return records;
//        }

        BigDecimal payPrice = order.getPayPrice();
        // 成本计算
        BigDecimal cost = BigDecimal.ZERO;
        List<OrderDetail> orderDetails = orderDetailService.getByOrderNo(orderNo);

        for (OrderDetail orderDetail : orderDetails) {
            ProductAttrValue productAttrValue = productAttrValueService.getByIdAndProductIdAndType(orderDetail.getAttrValueId(), orderDetail.getProductId(), ProductConstants.PRODUCT_TYPE_NORMAL);
            if (productAttrValue != null) {
                cost = cost.add(productAttrValue.getCost());
            }
        }
        if (cost.compareTo(BigDecimal.ZERO) == 0) {
            log.warn("计算佣金可疑，成本为0；orderNo=" + orderNo);
//            return records;
        }

        BigDecimal diff = payPrice.subtract(cost);
        if (diff.compareTo(BigDecimal.ZERO) <=0 ) {
            log.warn("计算佣金可疑，差价小于等于0；orderNo=" + orderNo);
//            return records;
            diff = BigDecimal.ZERO;
        }

        // 店主35%,店铺推荐人5%,店长5%,直接推荐人40%,间接推荐人5%
        SettleRate orderSettleRate = SettleRateConfig.getOrderSettleRate();
        Integer merId = order.getMerId();
        if (merId != null && merId != 0) {
            Merchant merchant = merchantService.getById(merId);
            if (merchant != null) {
                if (merchant.getOwnerUid() != null && merchant.getOwnerUid() != 0) {
                    //店主获得35%
                    BigDecimal brokerage = SettlementUtil.scale(diff.multiply(orderSettleRate.getMerOwnerRate()));
                    UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(merchant.getOwnerUid()).subUid(order.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER)
                            .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户下单店主获得佣金").price(brokerage).mark(StrUtil.format("用户下单店主获得佣金，分佣{}", brokerage))
                            .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
                    records.add(userBrokerageRecord);
                }

//                if (merchant.getSpreadUid() != null && merchant.getSpreadUid() != 0) {
//                    //店铺推荐人5%
//                    BigDecimal brokerage = SettlementUtil.scale(diff.multiply(orderSettleRate.getMerSpreadRate()));
//                    UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(merchant.getSpreadUid()).subUid(order.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER)
//                            .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户下单店铺推荐人获得佣金").price(brokerage).mark(StrUtil.format("用户下单店铺推荐人获得佣金，分佣{}", brokerage))
//                            .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
//                    records.add(userBrokerageRecord);
//                }

                if (merchant.getManagerUid() != null && merchant.getManagerUid() != 0) {
                    //店长5%
                    BigDecimal brokerage = SettlementUtil.scale(diff.multiply(orderSettleRate.getMerManagerRate()));
                    UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(merchant.getManagerUid()).subUid(order.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER)
                            .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户下单店长获得佣金").price(brokerage).mark(StrUtil.format("用户下单店长获得佣金，分佣{}", brokerage))
                            .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
                    records.add(userBrokerageRecord);
                }
            }
        }

        Integer buyerId = order.getUid();
        if (buyerId != null && buyerId != 0) {
            User buyer = userService.getById(buyerId);
            if (buyer != null) {
                Integer spreadUid = buyer.getSpreadUid();
                if (spreadUid != null && spreadUid != 0) {
                    User spreadUser = userService.getById(spreadUid);
                    if (spreadUser != null) {
                        //直接推荐人40%
                        if (spreadUser.getFirstPromoter()) {
                            BigDecimal brokerage = diff.multiply(orderSettleRate.getSpread1Rate());
                            UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(spreadUid).subUid(order.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER)
                                    .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户下单直接推荐人获得佣金").price(brokerage).mark(StrUtil.format("用户下单直接推荐人获得佣金，分佣{}", brokerage))
                                    .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
                            records.add(userBrokerageRecord);
                        }

                        if (spreadUser.getSpreadUid() != null && spreadUser.getSpreadUid() != 0) {
                            User secondSpreadUser = userService.getById(spreadUser.getSpreadUid());
                            if (secondSpreadUser != null && secondSpreadUser.getFirstPromoter() && secondSpreadUser.getSecondPromoter()) {
                                //间接推荐人5%
                                BigDecimal brokerage = diff.multiply(orderSettleRate.getSpread2Rate());
                                UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(secondSpreadUser.getId()).subUid(order.getUid()).linkNo(orderNo).linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER)
                                        .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户下单间接推荐人获得佣金").price(brokerage).mark(StrUtil.format("用户下单间接推荐人获得佣金，分佣{}", brokerage))
                                        .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
                                records.add(userBrokerageRecord);
                            }
                        }
                    }
                }
            }
        }
        //剩余的就是平台所得
        BigDecimal sumPrice = records.stream().map(m -> m.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal platformPrice = diff.subtract(sumPrice);
        UserBrokerageRecord userBrokerageRecord = UserBrokerageRecordBuilder.builder().uid(0).subUid(0).merId(GlobalConstants.PLATFORM_MER_ID).linkNo(orderNo)
                .linkType(BrokerageRecordConstants.BROKERAGE_RECORD_LINK_TYPE_ORDER)
                .type(BrokerageRecordConstants.BROKERAGE_RECORD_TYPE_ADD).title("用户下单平台获得佣金").price(platformPrice).mark(StrUtil.format("用户下单平台获得佣金，分佣{}", platformPrice))
                .status(BrokerageRecordConstants.BROKERAGE_RECORD_STATUS_CREATE).frozenTime(0).brokerageLevel(0).build();
        records.add(userBrokerageRecord);

        return records;
    }

}
